﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Amba.ImageMultiPicker.Services;
using Amba.ImageMultiPicker.ViewModels;
using Amba.ImageMultiPicker.ViewModels.Admin;
using Orchard;
using Orchard.Localization;
using Orchard.Media;
using Orchard.Media.Models;
using Orchard.Media.Services;
using Orchard.Themes;
using Amba.ImageMultiPicker.Extensions;
using Orchard.UI.Admin;

namespace Amba.ImageMultiPicker.Controllers
{
    [Themed(false)]
    [Admin]
    public class AdminController : Controller
    {
        private readonly IMediaService _mediaService;

        public IOrchardServices Services { get; set; }

        public AdminController(IOrchardServices services, IMediaService mediaService)
        {
            Services = services;
            _mediaService = mediaService;

            T = NullLocalizer.Instance;
        }

        public Localizer T { get; set; }

        private bool IsFolderExists(string mediaPath)
        {
            if (string.IsNullOrWhiteSpace(mediaPath))
                return true;
            var publicUrl = _mediaService.GetPublicUrl(mediaPath);
            var serverPath = Server.MapPath("~" + publicUrl);
            return Directory.Exists(serverPath);
        }

        public ActionResult Index(string mediaPath, string scope)
        {
            if (string.IsNullOrWhiteSpace(mediaPath))
                mediaPath = string.Empty;
            mediaPath = mediaPath.Trim();

            if (!IsFolderExists(mediaPath))
            {
                var emptyModel = new MediaFolderEditViewModel
                    {
                        IsFolderNotExists = true
                    };
                return View(emptyModel);
            }
            var mediaFolders = _mediaService.GetMediaFolders(mediaPath)
                .OrderBy(x => x.Name)
                .ToList();
            var mediaFiles = _mediaService.GetMediaFiles(mediaPath)
                .Where(x => x.Name.IsMatch(@"\.(jpg|jpeg|gif|png)$"))
                
                .AsParallel()
                .Select(x => CreateFileViewModel(mediaPath, x))
                .OrderBy(x => x.MediaFile.Name)
                .ToList();
            var model = new MediaFolderEditViewModel
                {
                    MediaFiles = mediaFiles, 
                    MediaFolders = mediaFolders, 
                    MediaPath = mediaPath,
                    Scope = scope,
                    BreadCrumbs = CreateBreadCrumbs(mediaPath)
                };
            ViewData["Service"] = _mediaService;
            return View(model);
        }

        private IEnumerable<BreadcrumbViewModel> CreateBreadCrumbs(string mediaPath)
        {
            var paths = mediaPath.Split('/', '\\');
            var result = new List<BreadcrumbViewModel>();
            for (int i = 0; i < paths.Count(); i++)
            {
                string path = "";
                for (int j = 0; j <= i; j++)
                {
                    path += (j != 0 ? "/" : "") + paths[j];
                }
                result.Add(new BreadcrumbViewModel(){FolderName = paths[i], MediaPath = path});
            }
            return result;
        }

        private ImageFileViewModel CreateFileViewModel(string mediaPath, MediaFile file)
        {
            var fileMediaPath = string.IsNullOrWhiteSpace(mediaPath) ? file.Name : mediaPath + "/" + file.Name;
            var result = new ImageFileViewModel
                {
                    MediaFile = file,
                    PublicUrl = _mediaService.GetPublicUrl(fileMediaPath)
                };
            var serverPath = Server.MapPath("~/" + result.PublicUrl);
            var size = ImageHeader.GetDimensions(serverPath);
            result.Width = size.Width;
            result.Height = size.Height;
            return result;
        }

        [HttpPost]
        public JsonResult CreateFolder(string path, string folderName)
        {
            if (!Services.Authorizer.Authorize(Permissions.ManageMedia))
            {
                return Json(new {Success = false, Message = T("Couldn't create media folder").ToString()});
            }

            try
            {
                _mediaService.CreateFolder(HttpUtility.UrlDecode(path), folderName);
                return Json(new {Success = true, Message = ""});
            }
            catch (Exception exception)
            {
                return
                    Json(new {Success = false, Message = T("Creating Folder failed: {0}", exception.Message).ToString()});
            }
        }
    }
}